package com.csxy.six;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    private final SecretKey secretKey;
    private final long expire;

    public JwtUtils(@Value("${jwt.secret}") String secret,
                    @Value("${jwt.expire}") long expire) {
        this.secretKey = Keys.hmacShaKeyFor(secret.getBytes());
        this.expire = expire;
    }

    public String generateToken(Long userId, String username, Long roleId, String roleName) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("roleId", roleId); // 存储角色ID
        claims.put("roleName", roleName); // 存储角色名称

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expire * 1000))
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();
    }

    public Claims getClaimsByToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    // 新增 parseToken 方法（与 getClaimsByToken 功能相同）
    public Claims parseToken(String token) {
        return getClaimsByToken(token);
    }

    public boolean isTokenExpired(String token) {
        return getClaimsByToken(token).getExpiration().before(new Date());
    }

    public Long getUserIdFromToken(String token) {
        return getClaimsByToken(token).get("userId", Long.class);
    }

    public String getUsernameFromToken(String token) {
        return getClaimsByToken(token).getSubject();
    }

    public Long getRoleIdFromToken(String token) {
        return getClaimsByToken(token).get("roleId", Long.class);
    }

    public String getRoleNameFromToken(String token) {
        return getClaimsByToken(token).get("roleName", String.class);
    }
}